﻿
using Cms.Core.Data.Model;
using Cms.Core.Infrastructure.Dependency;
using Cms.Core.Infrastructure.Runtime.Session;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cms.Core.Data.Audit
{
    /// <summary>
    /// 实体审计
    /// </summary>
    public class AuditEntityEntry
    {
        private readonly ICmsSession _session = null;
        public AuditEntityEntry(EntityEntry entry)
        {
            Entry = entry;
            _session = ServiceLocator.Instance.GetService<ICmsSession>();
        }

        public EntityEntry Entry { get; }
        public string TableName { get; set; }
        public Dictionary<string, object> KeyValues { get; } = new Dictionary<string, object>();
        public Dictionary<string, object> OldValues { get; } = new Dictionary<string, object>();
        public Dictionary<string, object> NewValues { get; } = new Dictionary<string, object>();
        public List<PropertyEntry> TemporaryProperties { get; } = new List<PropertyEntry>();

        public bool HasTemporaryProperties => TemporaryProperties.Any();

        public AuditEntry ToAudit()
        {
            var audit = new AuditEntry();
            audit.TableName = TableName;
            audit.CreateTime = DateTime.Now;
            audit.KeyValues = JsonConvert.SerializeObject(KeyValues);
            audit.OldValues = OldValues.Count == 0 ? null : JsonConvert.SerializeObject(OldValues);
            audit.NewValues = NewValues.Count == 0 ? null : JsonConvert.SerializeObject(NewValues);
            audit.EntityState = Entry.State;
            audit.CreateUserId = _session.GetUserId();
            return audit;
        }
    }
}
